//
//  ZYCStudentLeaveViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/7/26.
//

#import "ZYCStudentLeaveViewController.h"
#import "ZYCStudentLeaveBottomView.h"
#import "ZYCStudentLeaveCell.h"
#import <TZImagePickerController.h>
#import "ZYCSelectFutureDateView.h"
#import "ZYCRoleTreeModel.h"
#import "ZYCCommonSelectObjectPickerView.h"
#import "ZYCLeaveStudentModel.h"
#import "ZYCLeaveTypeModel.h"
#import "ZYCCommonBaseModel.h"
#import "ZYCNavigationController.h"
#import "ZYCStuLeavePersonViewController.h"
@interface ZYCStudentLeaveViewController ()<UITableViewDataSource,UITableViewDelegate,ZYCStudentLeaveBottomViewDelegate,ZYCCommonSelectObjectPickerViewDelegate,ZYCSelectFutureDateViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong) UIButton *comfirmButton;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) NSArray *treeArr;
@property (nonatomic, strong) ZYCStudentLeaveBottomView *bottomView;
@property (nonatomic, strong) NSMutableArray * selectedPhotos;
@property (nonatomic, strong) NSMutableArray * selectedAssets;
@property (nonatomic, strong) ZYCSelectFutureDateView *dateView;
@property (nonatomic, strong) ZYCCommonSelectObjectPickerView *leaveTypePickerView;

@property (nonatomic, strong) NSArray *studentArr;
@property (nonatomic, strong) NSMutableArray *leaveTypeArr;

@property (nonatomic, assign) ZYCLoginRoleType roleType;

@property (nonatomic, copy) NSString *studentUserId;
@property (nonatomic, copy) NSString *studentUserName;
@property (nonatomic, copy) NSString *relationshipLabel;
@property (nonatomic, copy) NSString *classId;
@property (nonatomic, copy) NSString *leaveDate;
@property (nonatomic, copy) NSString *durationLeave;
@property (nonatomic, copy) NSString *durationLeaveStr;

@property (nonatomic, strong) NSMutableArray * updateImageResults;
@property (nonatomic, assign) NSUInteger updateImageCount;
@property (nonatomic, copy) NSString *identity;


@end

@implementation ZYCStudentLeaveViewController

#pragma mark - setters
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"请假";
    self.identity = @"1";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.comfirmButton];
    [self.view addSubview:self.tableView];
    self.tableView.tableFooterView = self.bottomView;
    


}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCStudentLeaveCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCStudentLeaveCell class]) forIndexPath:indexPath];
    cell.dict = self.dataSource[indexPath.row];
    if (indexPath.row == 0) {
        cell.contentSting = self.studentUserName;
    }else if(indexPath.row == 1){
        cell.contentSting = self.leaveDate;
    }else if(indexPath.row == 2){
        cell.contentSting = self.durationLeaveStr;
    }
    return cell;
}
-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 23.0f;
    }
    return 0.01f;

}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return 10.0f;
    }
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45.0f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *v = [UIView new];
    v.backgroundColor = HEX_RGB(@"#F9F9F9");
    return v;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *v = [UIView new];
    v.backgroundColor = HEX_RGB(@"#F9F9F9");
    return v;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    ZYCWeakSelf
    if (indexPath.row == 0) {
        ZYCStuLeavePersonViewController *vc = [[ZYCStuLeavePersonViewController alloc] init];
        vc.titleString = @"推送学生";
        vc.selectStudentBlock = ^(ZYCRoleTreeModel * _Nonnull model) {
            weakSelf.studentUserId = model.r_id;
            weakSelf.studentUserName = model.label;
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        };
        [self.navigationController pushViewController:vc animated:YES];

    }else if(indexPath.row == 1){
        [self.dateView show];
    }else if(indexPath.row == 2){
        [self.leaveTypePickerView show];
    }
}



#pragma mark - ZYCCommonSelectObjectPickerViewDelegate
- (void)selectObjectPickerView:(ZYCCommonSelectObjectPickerView *)pickerView DidClickModel:(ZYCCommonBaseModel *)model{
    if (pickerView == self.leaveTypePickerView) {
        self.durationLeave = model.nameId;
        self.durationLeaveStr = model.name;
        NSIndexPath *indexPath= [NSIndexPath indexPathForRow:2 inSection:0];
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    }
    
}


#pragma mark - ZYCSelectFutureDateViewDelegate
- (void)didSelectedDateString:(NSString *)dateString{
    self.leaveDate = dateString;
    NSIndexPath *indexPath= [NSIndexPath indexPathForRow:1 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - ZYCStudentLeaveBottomViewDelegate
- (void)studentLeaveBottomViewDidClickAddPhoto{
    [self presentFliter];
}

- (void)presentFliter{
    ZYCWeakSelf
    UIAlertController *alert = [[UIAlertController alloc] init];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //判断权限
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied) {
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }];
            [alertC addAction:action1];
            [alertC addAction:action2];
            [self presentViewController:alertC animated:YES completion:nil];
        }else {
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:picker animated:YES completion:nil];
        }
    }];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf pushTZImagePickerViewController];

    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }];
    [alert addAction:photoAction];
    [alert addAction:albumAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)pushTZImagePickerViewController{
    ZYCWeakSelf
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 columnNumber:3 delegate:self pushPhotoPickerVc:YES];
    if (self.bottomView.selectedAssets.count > 0) {
        imagePickerVc.selectedAssets = self.bottomView.selectedAssets;
    }
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        weakSelf.selectedAssets = [NSMutableArray arrayWithArray:assets];
        weakSelf.selectedPhotos = [NSMutableArray arrayWithArray:photos];
        weakSelf.bottomView.selectedAssets = [NSMutableArray arrayWithArray:assets];
        weakSelf.bottomView.selectedPhotos = [NSMutableArray arrayWithArray:photos];

    }];
    imagePickerVc.barItemTextColor = [UIColor blackColor];
    [imagePickerVc.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor blackColor]}];
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.navigationBar.tintColor = [UIColor blackColor];
    imagePickerVc.naviBgColor = [UIColor whiteColor];
    imagePickerVc.navigationBar.translucent = NO;
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        [[TZImageManager manager] savePhotoWithImage:image completion:^(PHAsset *asset, NSError *error) {
            [self.selectedAssets addObject:asset];
            [self.selectedPhotos addObject:image];
            self.bottomView.selectedAssets = self.selectedAssets;
            self.bottomView.selectedPhotos = self.selectedPhotos;
        }];
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - getters
- (NSArray *)dataSource {
    if (!_dataSource) {
        _dataSource = @[@{@"title":@"请假学生",@"placeHolder":@"请选择请假学生"},
                        @{@"title":@"请假日期",@"placeHolder":@"请选择日期"},
                        @{@"title":@"请假时长",@"placeHolder":@"请选择请假时长"}];
    }
    return _dataSource;
}

- (UIButton *)comfirmButton {
    if (!_comfirmButton) {
        _comfirmButton = [[UIButton alloc] init];
        [_comfirmButton setTitle:@"提交" forState:UIControlStateNormal];
        [_comfirmButton setTitleColor:HEX_RGB(kTitleWhiteColor) forState:UIControlStateNormal];
        _comfirmButton.titleLabel.font = kCustomFont(@"PingFangSC-Regular", 15.0f);
        [_comfirmButton addTarget:self action:@selector(clickRightItem:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _comfirmButton;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, kScreenHeight - kNavBarAndStatusBarHeight) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCStudentLeaveCell class] forCellReuseIdentifier:NSStringFromClass([ZYCStudentLeaveCell class])];
        _tableView.estimatedRowHeight = 105;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
    }
    return _tableView;
}


- (ZYCStudentLeaveBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[ZYCStudentLeaveBottomView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 600)];
        _bottomView.delegate = self;
    }
    return _bottomView;
}

- (NSMutableArray *)selectedPhotos {
    if (!_selectedPhotos) {
        _selectedPhotos = [[NSMutableArray alloc] init];
    }
    return _selectedPhotos;
}

- (NSMutableArray *)selectedAssets {
    if (!_selectedAssets) {
        _selectedAssets = [[NSMutableArray alloc] init];
    }
    return _selectedAssets;
}
- (ZYCSelectFutureDateView *)dateView{
    if (!_dateView) {
        _dateView = [[ZYCSelectFutureDateView alloc]init];
        _dateView.delegate = self;
        [self.view addSubview:_dateView];
    }
    return _dateView;
}

- (NSMutableArray *)leaveTypeArr {
    if (!_leaveTypeArr) {
        _leaveTypeArr = [[NSMutableArray alloc] init];
        {
            ZYCCommonBaseModel *model = [ZYCCommonBaseModel new];
            model.name = @"上午假";
            model.nameId = @"1";
            [_leaveTypeArr addObject:model];
        }
        {
            ZYCCommonBaseModel *model = [ZYCCommonBaseModel new];
            model.name = @"下午假";
            model.nameId = @"2";
            [_leaveTypeArr addObject:model];
        }
        {
            ZYCCommonBaseModel *model = [ZYCCommonBaseModel new];
            model.name = @"全天假";
            model.nameId = @"3";
            [_leaveTypeArr addObject:model];
        }
    }
    return _leaveTypeArr;
}
- (ZYCCommonSelectObjectPickerView *)leaveTypePickerView{
    if (!_leaveTypePickerView) {
        _leaveTypePickerView = [[ZYCCommonSelectObjectPickerView alloc]init];
        _leaveTypePickerView.tipString = @"请选择假期类型";
        _leaveTypePickerView.dataSource = self.leaveTypeArr;
        _leaveTypePickerView.delegate = self;
        [self.view addSubview:_leaveTypePickerView];
    }
    return _leaveTypePickerView;
}


     

- (NSArray *)studentArr {
    if (!_studentArr) {
        _studentArr = [[NSArray alloc] init];
    }
    return _studentArr;
}

- (NSArray *)treeArr {
    if (!_treeArr) {
        _treeArr = [[NSArray alloc] init];
    }
    return _treeArr;
}



#pragma mark - private action
//提交
- (void)clickRightItem:(UIButton *)sender{
    if (self.bottomView.selectedPhotos.count > 0) {
        self.updateImageCount = 0;
        self.updateImageResults = [NSMutableArray arrayWithCapacity:0];
        for (UIImage *image in self.bottomView.selectedPhotos) {
            self.updateImageCount ++;
            [self uploadWithImage:image];
        }
    }else{
        [self addLeave];
    }

}

- (void)addLeave{
    if (self.updateImageCount != 0) {// 防止发布多条
        return;
    }
    

    if (self.studentUserId.length == 0 || self.studentUserName.length == 0) {
        [MrjToast makeToast:@"请选择请假学生" makeView:self.view];
        return;
    }
    
    if (self.leaveDate.length == 0) {
        [MrjToast makeToast:@"请选择请假日期" makeView:self.view];
        return;
    }
    if (self.durationLeave.length == 0) {
        [MrjToast makeToast:@"请选择请假时长" makeView:self.view];
        return;
    }
    if (self.bottomView.leaveContent == 0) {
        [MrjToast makeToast:@"请输入请假说明" makeView:self.view];
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.studentUserId forKey:@"studentUserId"];
    [params setObject:self.studentUserName forKey:@"studentUserName"];
    [params setObject:self.leaveDate forKey:@"leaveDate"];
    [params setObject:self.durationLeave forKey:@"durationLeave"];
    [params setObject:self.bottomView.leaveContent forKey:@"leaveContent"];
    [params setObject:self.identity forKey:@"identity"];
    if (self.updateImageResults.count > 0) {
        [params setObject:self.updateImageResults forKey:@"files"];
    }
    
    [MrjSVProgressHUD showWithStatus:@"提交中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_AddLeaveByTeacher requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(id  _Nullable responseObject) {
        [MrjSVProgressHUD dismiss];
        if (SUCCESS(responseObject[@"code"])) {
            [MrjSVProgressHUD showSuccessWithStatus:responseObject[@"message"]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else{
            [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}



// 上传图片
- (void)uploadWithImage:(UIImage *)image{
    NSString *urlStr = [NSString stringWithFormat:@"%@/zd-system-service/%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],Common_Post_Upload];
    [[URLManager sharedURLManager] POST:urlStr parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSString *fileName;
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat = @"MMddHHmmss";
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        fileName = [NSString stringWithFormat:@"%@.png",dateString];//以这种格式防止上传的图片重复覆盖
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (SUCCESS(responseObject[@"code"])) {
            NSLog(@"%@",responseObject);
            self.updateImageCount --;
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:responseObject[@"body"][@"fileName"] forKey:@"fileName"];
            [dic setObject:responseObject[@"body"][@"url"] forKey:@"filePath"];
            [self.updateImageResults addObject:dic];
            
            //
            [self addLeave];
            
        }else{
            [MrjToast makeToast:@"图片上传失败" makeView:self.view];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
